//
//  UserId.m
//  playSerengetiMobile1
//
//  Created by Lita Gratrix on 10/25/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "MainView.h"
#import "UserHome.h"
#import "TeamProfile.h"
#import "LocationProfile.h"
#import "JSON/JSON.h"


#define kViewTag				1		// for tagging our embedded controls for removal at cell recycle time

#define kFriendSection			0		// for selecting the table section containing friends
#define kTeamSection			1		// for selecting the table section containing teams
#define kFriendInviteSection	2		// for selecting the table section containing friend invites
#define kTeamInviteSection		3		// for selecting the table section containing team invites
#define kNearbyLocationsSection	4		// for selecting the table section containing nearby locationss

#define LOCATION_ACCURACY		100.0
#define LOCATION_TIMEOUT		30.0

#define ROW_HEIGHT_FOR_TABLE	30

static NSString *kSectionTitleKey = @"sectionTitleKey";
static NSString *kSourceKey = @"sourceKey";
static NSString *kViewKey = @"viewKey";


@implementation UserHome

@synthesize displayNameLabel, emailLabel, userProfileTableView;
@synthesize userHomeConnection, nearbyLocationsConnection;
@synthesize friendInvites, teamInvites, friends, teams, nearbyLocations, profile;
@synthesize latitude, longitude;
@synthesize tableSourceArray;
@synthesize locationController, appDelegate;


- (void)viewDidLoad{
    [super viewDidLoad];
	
	self.appDelegate = (playSerengetiMobile1AppDelegate *)[[UIApplication sharedApplication] delegate];
	
	/*
	NSArray *currentSubviews = appDelegate.window.subviews;
	UIView *viewToRemove = [currentSubviews objectAtIndex:[currentSubviews count] -1];
	if([viewToRemove isKindOfClass:[MainView class]]){
	    [viewToRemove removeFromSuperview];
	}
	*/
	
	responseData = [[NSMutableData data] retain];
	NSString *URLString = [NSString stringWithFormat:@"%@user/%d/json", appDelegate.baseURL, appDelegate.loggedInAs];
//	NSLog(@"userHomeConnection URLString is %@\n", URLString);
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
	userHomeConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	
	self.friends = [[NSMutableArray alloc] init];
	self.teams = [[NSMutableArray alloc] init];
	self.friendInvites = [[NSMutableArray alloc] init];
	self.teamInvites = [[NSMutableArray alloc] init];
	self.nearbyLocations = [[NSMutableArray alloc] init];
	
	self.tableSourceArray = [NSArray arrayWithObjects:
							 [NSDictionary dictionaryWithObjectsAndKeys:
							  @"Friends", kSectionTitleKey,
							  self.friends, kSourceKey,
							  nil],
							 
							 [NSDictionary dictionaryWithObjectsAndKeys:
							  @"Teams", kSectionTitleKey,
							  self.teams, kSourceKey,
							  nil],
							 
							 [NSDictionary dictionaryWithObjectsAndKeys:
							  @"Friend Invites", kSectionTitleKey,
							  self.friendInvites, kSourceKey, 
							  nil],
							 
							 [NSDictionary dictionaryWithObjectsAndKeys:
							  @"Team Invites", kSectionTitleKey,
							  self.teamInvites, kSourceKey,
							  nil],
							 
							 [NSDictionary dictionaryWithObjectsAndKeys:
							  @"Nearby Locations", kSectionTitleKey,
							  self.nearbyLocations, kSourceKey,
							  nil],
							 nil];
	
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

- (void)checkInSubmit:(id)sender{
//	NSLog(@"teams has %d elements, and nearbyLocations had %d elements\n", [teams count], [nearbyLocations count]);
	[appDelegate loadCheckInViewWithTeams:teams andLocations:nearbyLocations];
}


- (void)dealloc {
    [super dealloc];
}

#pragma mark -
#pragma mark populateViewDataMethods

-(void)populateViewData:(NSDictionary *)parsedData{
	NSDictionary *userDictionary = [parsedData objectForKey:@"user"];
	NSMutableArray *friendArray =[parsedData objectForKey:@"friends"];
	NSMutableArray *teamArray = [parsedData objectForKey:@"teams"];
	NSDictionary *invitesDictionary = [parsedData objectForKey:@"invites"];
	
	[self populateUser:(NSDictionary *)userDictionary];
	[self populateFriends:(NSMutableArray *)friendArray];
	[self populateTeams:(NSMutableArray *)teamArray];
	[self populateInvites:(NSDictionary*)invitesDictionary];
	[self getCurrentLocation];

}

- (void)populateUser:(NSDictionary *)userDictionary{
//	NSLog(@"Entering populateUser.\n");
	profile = [[User alloc] init];

	profile.email = [userDictionary objectForKey:@"email"];
	profile.name = [userDictionary objectForKey:@"name"];

	displayNameLabel.text = profile.name;
	
	emailLabel.text = profile.email;
}

- (void)populateFriends:(NSMutableArray *)friendArray{
//	NSLog(@"Entering populateFriends.\n");
//	NSLog(@"friendArray contains %d elements.\n", [friendArray count]);
	if([friendArray count] == 0){
		//Do something
	} else {
		[friends removeAllObjects];
		int i;
		for (i = 0; i < [friendArray count]; i++){
			User *friend = [[User alloc] init];
			NSDictionary *friendsDic = [friendArray objectAtIndex:i];
			friend.userId = [[friendsDic objectForKey:@"id"] integerValue];
			friend.name = [friendsDic objectForKey:@"name"];
//			NSLog(@"Adding friend %d, %@ to friends.\n", friend.userId, friend.name);
			[friends addObject: friend];
		}
	}
//	NSLog(@"friends has %d objects\n", [friends count]);
}

- (void)populateTeams:(NSMutableArray *)teamArray{
//	NSLog(@"Entering populateTeams.\n");
//	NSLog(@"teamArray contains %d elements.\n", [teamArray count]);
	if([teamArray count] == 0){
		//Do something
	} else {
		[teams removeAllObjects];
		int i;
		for (i = 0; i < [teamArray count]; i++){
			Team *team = [[Team alloc] init];
			NSDictionary *teamDic = [teamArray objectAtIndex:i];
			team.teamId = [[teamDic objectForKey:@"id"] integerValue];
			team.teamName = [teamDic objectForKey:@"name"];
//			NSLog(@"Adding team %d, %@ to team.\n", team.teamId, team.teamName);
			[teams addObject: team];
//			[team release];
//			team = nil;
		}
	}
}

- (void)populateInvites:(NSDictionary *)inviteDictionary{
//	NSLog(@"Entering populateInvites.\n");
	
	NSMutableArray *friendInviteArray = [inviteDictionary objectForKey:@"friendInvites"];
	NSMutableArray *teamInviteArray = [inviteDictionary objectForKey:@"teamInvites"];
	
	[self populateFriendInvites:(NSMutableArray *) friendInviteArray];
	[self populateTeamInvites:(NSMutableArray *) teamInviteArray];
}

- (void)populateFriendInvites:(NSMutableArray *)friendInviteArray{
//	NSLog(@"Entering populateFriendInvites.\n");
//	NSLog(@"friendInviteArray contains %d elements.\n", [friendInviteArray count]);
	if([friendInviteArray count] == 0){
		//Do something
	} else {
		[friendInvites removeAllObjects];
		int i;
		for (i = 0; i < [friendInviteArray count]; i++){
			User *friendInvite = [User alloc];
			NSDictionary *friendInviteDic = [friendInviteArray objectAtIndex:i];
			friendInvite.userId = [[friendInviteDic objectForKey:@"id"] integerValue];
			friendInvite.name = [friendInviteDic objectForKey:@"name"];
//			NSLog(@"adding friendInvite %d, %@ to friendInvites\n", friendInvite.userId, friendInvite.name);
			[friendInvites addObject: friendInvite];
		}
	}
}

- (void)populateTeamInvites:(NSMutableArray *)teamInviteArray{
//	NSLog(@"Entering populateTeamInvites");
//	NSLog(@"teamInviteArray contains %d elements \n", [teamInviteArray count]);
	if([teamInviteArray count] == 0){
		//Do something
	} else {
		[teamInvites removeAllObjects];
		int i;
		for (i = 0; i < [teamInviteArray count]; i++){
			Team *teamInvite = [Team alloc];
			NSDictionary *teamInviteDic = [teamInviteArray objectAtIndex:i];
			teamInvite.teamId = [[teamInviteDic objectForKey:@"id"] integerValue];
			teamInvite.teamName = [teamInviteDic objectForKey:@"name"];
//			NSLog(@"adding teamInvite %d, %@ to teamInvites\n", teamInvite.teamId, teamInvite.teamName);
			[teamInvites addObject: teamInvite];
		}
	}
}

- (void)getNearbyLocations{
//	NSLog(@"Entering getNearbyLocations\n");
	responseData = [[NSMutableData data] retain];
	NSString *URLString = [NSString stringWithFormat:@"%@location/getNearbyLocations?latitude=%f&longitude=%f", appDelegate.baseURL, latitude, longitude];
//	NSLog(@"String to request nearby locations reads %@\n", URLString);
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
	nearbyLocationsConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];		
}

- (void)populateNearbyLocations:(NSDictionary *)parsedData{
//	NSLog(@"Entering populateNearbyLocations\n");
	NSMutableArray *nearbyLocationsArray = [parsedData objectForKey:@"locations"];
//	NSLog(@"nearbyLocationsArray has %d elements\n", [nearbyLocationsArray count]);
	if([nearbyLocationsArray count] == 0){
		//Do something
	}else{
		[nearbyLocations removeAllObjects];
		int i;
		for(i = 0; i < [nearbyLocationsArray count]; i++){
//			NSLog(@"creating location for index %d\n", i);
			Location *location = [[Location alloc] init];
			NSDictionary *locationDic = [nearbyLocationsArray objectAtIndex:i];
			location.locationId = [[locationDic objectForKey:@"id"] integerValue];
			location.locationName = [locationDic objectForKey:@"name"];
			location.phoneNumber = [locationDic objectForKey:@"phoneNumber"];
			location.latitude = [[locationDic objectForKey:@"latitude"] doubleValue];
			location.longitude = [[locationDic objectForKey:@"longitude"] doubleValue];
			location.street = [locationDic objectForKey:@"street"];
			location.city = [locationDic objectForKey:@"city"];
			location.state = [locationDic objectForKey:@"state"];
			location.zipCode = [locationDic objectForKey:@"zipcode"];
			location.description = [locationDic objectForKey:@"description"];
			NSDictionary *teamDic = [locationDic objectForKey:@"owner"];
			location.teamOwner = [self populateTeamOwner:(NSDictionary *)teamDic];
//			NSLog(@"created location that looks like [%d, %@, %f, %f,", location.locationId, location.locationName, location.latitude, location.longitude);
//			NSLog(@"%@, %@, %@, %@, %@,", location.phoneNumber, location.street, location.city, location.state, location.zipCode);
//			NSLog(@"%@, {%d, %@}]\n", location.description, location.teamOwner.teamId, location.teamOwner.teamName);
			[nearbyLocations addObject: location];
		}
//		NSLog(@"nearbyLocations has %d objects", [nearbyLocations count]);
	}
	[self.userProfileTableView reloadData];
}

- (Team *)populateTeamOwner:(NSDictionary *)teamDic{
//	NSLog(@"Entering populateTeamOwner\n");
	Team *teamOwner = [[Team alloc] init];
	teamOwner.teamId = [[teamDic objectForKey:@"id"] integerValue];
	teamOwner.teamName = [teamDic objectForKey:@"name"];
//	NSLog(@"Returning teamOwner that looks like: [%d , %@]\n", teamOwner.teamId, teamOwner.teamName);
	return teamOwner;
}

#pragma mark -
#pragma mark Location Methods

- (void)getCurrentLocation{
//	NSLog(@"Entering getCurrentLocation\n");
	if(TARGET_IPHONE_SIMULATOR){
		latitude = 33.969326;
		longitude = -118.414387;
		[self getNearbyLocations];
	} else {
		locationController = [[SerengetiCLController alloc] init];
		locationController.delegate = self;
		locationController.locationManager.desiredAccuracy =  LOCATION_ACCURACY;
		[locationController.locationManager startUpdatingLocation];
		[self performSelector:@selector(stopUpdatingLocation:) withObject:@"Timed Out" afterDelay:LOCATION_TIMEOUT];
	}
}

- (void)locationUpdate:(CLLocation *)location {
//	NSLog(@"Entering locationUpdate.\n");
//	NSLog(@"location is %@", location);
//	NSLog(@"location.coordinate.latitude = %f\n", location.coordinate.latitude);
	self.latitude = location.coordinate.latitude;
//	NSLog(@"self.latitude = %f\n", self.latitude);
	self.longitude = location.coordinate.longitude;	
	[self getNearbyLocations];
}

- (void)locationError:(NSError *)error {
	NSLog(@"Error capturing locaiton: %@", [error description]);
}

- (void)stopUpdatingLocation:(NSString *)state {
	[locationController.locationManager stopUpdatingLocation];
	locationController.locationManager.delegate = nil;
}


#pragma mark -
#pragma mark NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	if(connection == userHomeConnection){
		NSLog(@"Connection to userHome failed: %@\n", [error description]);
	}else if (connection == nearbyLocationsConnection){
		NSLog(@"Connection to nearbyLocations failed: %@\n", [error description]);
	}
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	if(connection == userHomeConnection){
//		NSLog(@"Entering connectionDidFinishLoading with userHomeConenction\n");
		[connection release];
	
		NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//		NSLog(@"responseString reads: %@\n", responseString);
	
		[responseData release];
		responseData = nil;
	
		NSDictionary *parsedData = [responseString JSONValue];
	
		[responseString release];
	
		if (parsedData == nil) {
			displayNameLabel.text = [NSString stringWithFormat:@"Error in returned data.\n"];
		} else {
			[self populateViewData:(NSDictionary *)parsedData];
		}
	}else if (connection == nearbyLocationsConnection){
//		NSLog(@"Entering connectionDidFinishLoading with nearbyLocationConenction\n");
		[connection release];
		
		NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//		NSLog(@"responseString for nearbyLocationsConnection reads: %@\n", responseString);
		
		[responseData release];
		responseData = nil;
		
		NSDictionary *parsedData = [responseString JSONValue];
		
		[responseString release];
		
		if (parsedData == nil) {
			NSLog(@"Error in returned nearby location data.\n");
		} else {
			[self populateNearbyLocations:(NSDictionary *)parsedData];
		}
	}
}	

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return [tableSourceArray count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return [[self.tableSourceArray objectAtIndex: section] valueForKey:kSectionTitleKey];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//	NSLog(@"Entering numberOfRowsInSection:%d", section);
	NSMutableArray *sectionData = [[self.tableSourceArray objectAtIndex:section] valueForKey:kSourceKey];
//	NSLog(@"number of expected rows: %d.\n", [sectionData count]);
	return [sectionData count];
}

// to determine specific row height for each cell, override this.
//In this example, each row is determined by its subviews that are embedded.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return ROW_HEIGHT_FOR_TABLE;
	//return ([indexPath row] == 0) ? 50.0 : 38.0;
}

// to determine which UITableViewCell to be used on a given row.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	UITableViewCell *cell = nil;
	User *aUser;
	Team *thisTeam;
	Location *aLocation;
	
	if(indexPath.section == kFriendSection || indexPath.section == kFriendInviteSection){
		aUser = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
	} else if (indexPath.section == kTeamSection || indexPath.section == kTeamInviteSection){
		thisTeam = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
	} else if (indexPath.section == kNearbyLocationsSection){
		aLocation = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
	}
		
	static NSString *kDisplayCell_ID = @"DisplayCellID";
	cell = [self.userProfileTableView dequeueReusableCellWithIdentifier:kDisplayCell_ID];
	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kDisplayCell_ID] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	}
	else
	{
		// the cell is being recycled, remove old embedded controls
		UIView *viewToRemove = nil;
		viewToRemove = [cell.contentView viewWithTag:kViewTag];
		if (viewToRemove){
			[viewToRemove removeFromSuperview];
		}
	}
		
	UIControl *control = [[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kViewKey];
	[cell.contentView addSubview:control];
		
	if(indexPath.section == kFriendSection || indexPath.section == kFriendInviteSection){
		cell.textLabel.text = aUser.name;
//		[aUser release];
//		aUser = nil;
	}else if(indexPath.section == kTeamSection || indexPath.section == kTeamInviteSection){
		cell.textLabel.text = thisTeam.teamName;
//		[thisTeam release];
//		thisTeam = nil;
	}else if(indexPath.section == kNearbyLocationsSection){
		cell.textLabel.text = aLocation.locationName;
//		[aLocation release];
//		aLocation = nil;
	}
	
	return cell;
}

- (void)switchAction:(id)sender
{
	// NSLog(@"switchAction: value = %d", [sender isOn]);
}

- (void)pageAction:(id)sender
{
	// NSLog(@"pageAction: current page = %d", [sender currentPage]);
}

#pragma mark -
#pragma mark UITableViewDelegate

// the table's selection has changed, switch to that item's UIViewController
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	
	User *aUser;
	Team *aTeam;
	Location *aLocation;
	
	if(indexPath.section == kFriendSection || indexPath.section == kFriendInviteSection){
		aUser = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
		
		UserProfile *aUserProfileView = [[UserProfile alloc] initWithNibName:@"UserProfile" bundle:nil];
		aUserProfileView.userId = aUser.userId;
//		[aUser release];
//		aUser = nil;
		[self.view addSubview:aUserProfileView.view]; 
		
	} else if (indexPath.section == kTeamSection || indexPath.section == kTeamInviteSection){
		aTeam = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
		
		TeamProfile *aTeamProfileView = [[TeamProfile alloc] initWithNibName:@"TeamProfile" bundle:nil];
		aTeamProfileView.teamId = aTeam.teamId;
//		[aTeam release];
//		aTeam = nil;
		[self.view addSubview:aTeamProfileView.view]; 
		
	} else if (indexPath.section == kNearbyLocationsSection){
		aLocation = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
		
		LocationProfile *aLocationProfileView = [[LocationProfile alloc] initWithNibName:@"LocationProfile" bundle:nil];
		aLocationProfileView.locationId = aLocation.locationId;
		
//		[aLocation release];
//		aLocation = nil;
		[self.view addSubview:aLocationProfileView.view];
	}
		
}

@end
